//
//  FQDArticleDetailViewController.m
//  FakeQDaily
//
//  Created by mewxiv on 8/20/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import "FQDArticleDetailViewController.h"
#import "UIViewController+FQDStatusBar.h"
#import "FQDCommentViewController.h"
#import "FQDDetailToolBar.h"
#import "FQDDetailToolBarButton.h"
#import "FQDArticleLoadingView.h"
#import "MBProgressHUD+FQDExtension.h"
#import "FQDRestModel.h"
#import "QDailyAPI.h"
#import "QDailyAPIConstants.h"
#import "FQDPraiseHistory.h"
#import "FQDAccountManager.h"
#import "FQDSimpleFeedCellItemProvider.h"
#import "FQDArticleFeedBaseViewController.h"

#import "Masonry.h"
#import "YYModel.h"
#import "FQDPhotoViewerController.h"
#import "WebViewJavascriptBridge.h"

static CGSize const ArticleToolBarSize = (CGSize){186.0f, 69.0f};
static NSString *const kQDailyPageReadyHandlerName = @"qdaily::pageReady";
static NSString *const kQDailyGotoPageHandlerName = @"qdaily::gotoPage";
static NSString *const kQDailyPicsPreviewHandlerName = @"qdaily::picsPreview";

@interface FQDArticleDetailViewController () <UIWebViewDelegate,
                                              UIScrollViewDelegate>

// 文章内容webView
@property (nonatomic, strong) UIWebView *detailWebView;
// 返回按钮
@property (nonatomic, strong) UIButton *backButton;
// 右下角工具栏
@property (nonatomic, strong) FQDDetailToolBar *detailToolBar;
// 评论按钮
@property (nonatomic, strong) FQDDetailToolBarButton *commentButton;
// 点赞按钮
@property (nonatomic, strong) FQDDetailToolBarButton *likeButton;
// Loading界面
@property (nonatomic, strong) FQDArticleLoadingView *loadingView;
// Js与Objective-C互调的bridge
@property (nonatomic, strong) WebViewJavascriptBridge *bridge;

@end

@implementation FQDArticleDetailViewController

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.fqd_statusBarStyle = FQDStatusBarStyleLightTranslucent;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupDetailWebView];
    [self setupDetailToolbar];
    [self updateDetailToolbar];
    [self setupWebViewBridge];
    [self startLoading];
}

- (void)setupDetailWebView
{
    self.detailWebView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    self.detailWebView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.detailWebView.delegate = self;
    self.detailWebView.scrollView.delegate = self;
    self.detailWebView.backgroundColor = FQDFeedContainerBackgroundColor;
    [self.view addSubview:self.detailWebView];

}

- (void)setupDetailToolbar
{
    UIImage *backImage = [UIImage imageNamed:@"navigation_back_round_normal"];
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.backButton setImage:backImage forState:UIControlStateNormal];
    [self.view addSubview:self.backButton];
    
    [self.backButton addTarget:self
                        action:@selector(backToHome:)
              forControlEvents:UIControlEventTouchUpInside];
    
    WeakSelf;
    [self.backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view).offset(14);
        make.bottom.equalTo(weakSelf.view).offset(-4);
    }];
    
    UIImage *commentImage = [UIImage imageNamed:@"toolbarComment"];
    FQDDetailToolBarButton *commentButton =
    [FQDDetailToolBarButton buttonWithIcon:commentImage
                                detailText:@""
                                    target:self
                                    action:@selector(showCommentView:)];
    self.commentButton = commentButton;
    
    UIImage *likeImage = [UIImage imageNamed:@"toolbarLike"];
    FQDDetailToolBarButton *likeButton =
    [FQDDetailToolBarButton buttonWithIcon:likeImage
                                detailText:@""
                                    target:self
                                    action:@selector(likeThisArticle:)];
    self.likeButton = likeButton;
    
    UIImage *shareImage = [UIImage imageNamed:@"toolbarShare"];
    FQDDetailToolBarButton *shareButton =
    [FQDDetailToolBarButton buttonWithIcon:shareImage
                                detailText:@""
                                    target:self
                                    action:@selector(shareThisArticle:)];
    
    NSArray *barButtons = @[commentButton, likeButton, shareButton];
    
    self.detailToolBar = [[FQDDetailToolBar alloc] initWithBarButtons:barButtons];
    [self.view addSubview:self.detailToolBar];
    
    [self.detailToolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.view);
        make.bottom.equalTo(weakSelf.view);
        make.size.mas_equalTo(ArticleToolBarSize);
    }];
}

- (void)updateDetailToolbar
{
    FQDAccountManager *accountManager = [FQDAccountManager sharedManager];
    FQDPost *post = self.post;
    NSString *userId = accountManager.currentUserId;
    NSInteger commentCount = post.comment_count;
    NSString *commentNumStr = (commentCount == 0) ? @"" : [@(commentCount) stringValue];
    self.commentButton.detailTextLabel.text = commentNumStr;
    
    FQDPraiseHistory *praiseHistory = [FQDPraiseHistory sharedHistory];
    BOOL hasPraised = [praiseHistory userHasPraised:post.ID userId:userId];
    NSInteger praiseCount = post.praise_count;
    NSString *praiseNumStr = (praiseCount == 0) ? @"" : [@(praiseCount) stringValue];
    NSString *likeImageName = (hasPraised) ? @"toolbarLiked" : @"toolbarLike";
    UIImage *likeImage = [UIImage imageNamed:likeImageName];
    self.likeButton.iconImageView.image = likeImage;
    self.likeButton.detailTextLabel.text = praiseNumStr;
}

- (void)setupWebViewBridge
{
//    [WebViewJavascriptBridge enableLogging];
    
    NSBundle *resourceBundle = [NSBundle bundleForClass:[WebViewJavascriptBridge class]];
    self.bridge = [WebViewJavascriptBridge bridgeForWebView:self.detailWebView
                                            webViewDelegate:self
                                                    handler:nil
                                             resourceBundle:resourceBundle];
    [self.bridge registerHandler:kQDailyPageReadyHandlerName handler:^(id data, WVJBResponseCallback responseCallback) {
        responseCallback(data);
    }];
    
    [self.bridge registerHandler:kQDailyGotoPageHandlerName handler:^(id data, WVJBResponseCallback responseCallback) {
        NSString *type = data[@"type"];
        if ([type isEqualToString:@"tag"]) {
            NSDictionary *param = data[@"params"];
            NSString *tagId = param[@"id"];
            NSString *title = param[@"title"];
            
            NSString *const kTaggedArticleCacheId = @"tagged_articles";
            FQDSimpleFeedCellItemProvider *provider = [[FQDSimpleFeedCellItemProvider alloc] init];
            provider.cacheId = kTaggedArticleCacheId;
            provider.feedId = tagId;
            [provider setFetchFeedBlock:^(NSString *feedId, NSString *cursorKey, QDailyAPICompleteBlock completion) {
                [[QDailyAPI sharedAPI] getTaggedArticleList:tagId key:cursorKey completion:completion];
            }];
            
            FQDArticleFeedBaseViewController *afbVC = [[FQDArticleFeedBaseViewController alloc] init];
            afbVC.title = title;
            afbVC.provider = provider;
            [self.navigationController pushViewController:afbVC animated:YES];
        }
        responseCallback(data);
    }];
    
    [self.bridge registerHandler:kQDailyPicsPreviewHandlerName handler:^(id data, WVJBResponseCallback responseCallback) {
        [self presentPhotoBrowser:data[@"pics"] currentIdx:[data[@"cur"] integerValue]];
        responseCallback(data);
    }];

}

- (void)startLoading
{
    WeakSelf;
    [[QDailyAPI sharedAPI] getArticleDetail:self.post.ID completion:^(id responseObject, NSError *error) {
        NSNumber *status = [responseObject valueForKeyPath:@"meta.status"];
        if ([status integerValue] == 200) {
            id response = responseObject[@"response"];
            NSURL *baseURL = [NSURL URLWithString:QDailyBaseURL];
            FQDArticleDetail *articleDetail = [FQDArticleDetail yy_modelWithJSON:response[@"article"]];
            [weakSelf.detailWebView loadHTMLString:articleDetail.body baseURL:baseURL];
        } else {
            FQDLog(@"获取文章数据失败");
        }
    }];
    
    [[QDailyAPI sharedAPI] getArticleInfo:self.post.ID completion:^(id responseObject, NSError *error) {
        NSNumber *status = [responseObject valueForKeyPath:@"meta.status"];
        if ([status integerValue] == 200) {
            id response = responseObject[@"response"];
            FQDPost *post = [FQDPost yy_modelWithJSON:response[@"post"]];
            weakSelf.post = post;
            [weakSelf showDetailToolBar];
            [weakSelf updateDetailToolbar];
        } else {
            FQDLog(@"获取文章信息失败");
        }
    }];
    
    self.loadingView = [[FQDArticleLoadingView alloc] initWithFrame:self.view.bounds];
    [self.loadingView startLoading];
    [self.view addSubview:self.loadingView];
    
    [self.view bringSubviewToFront:self.detailToolBar];
    [self.view bringSubviewToFront:self.backButton];
    
    self.backButton.alpha = 0;
    self.detailToolBar.alpha = 0;
    self.detailWebView.alpha = 0;
    
    [UIView animateWithDuration:0.3f animations:^{
        self.backButton.alpha = 1.0f;
    }];
}

- (void)endLoading:(BOOL)success
{
    if (success) {
        [UIView animateWithDuration:0.3f animations:^{
            self.loadingView.alpha = 0;
            self.detailWebView.alpha = 1.0f;
        } completion:^(BOOL finished) {
            [self.loadingView removeFromSuperview];
        }];
    }
}

- (void)showDetailToolBar
{
    [UIView animateWithDuration:0.3f animations:^{
        self.detailToolBar.alpha = 1.0f;
    }];
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation
{
    return UIStatusBarAnimationSlide;
}

#pragma mark - Photo Browser
- (void)presentPhotoBrowser:(NSArray *)pics currentIdx:(NSInteger)currentIdx
{
    NSMutableArray *photos = [NSMutableArray array];
    for (id picInfo in pics) {
        NSURL *photoURL = nil;
        NSString *photoCaption = @"";
        if ([picInfo isKindOfClass:[NSDictionary class]]) {
            photoURL = [NSURL URLWithString:picInfo[@"url"]];
            photoCaption = picInfo[@"text"];
        } else {
            photoURL = [NSURL URLWithString:picInfo];
        }
        
        if (photoURL) {
            MWPhoto *photo = [[MWPhoto alloc] initWithURL:photoURL];
            photo.caption = photoCaption;
            [photos addObject:photo];
        }
    }
    
    FQDPhotoViewerController *browser = [[FQDPhotoViewerController alloc] initWithPhotos:[photos copy]
                                                          currentIndex:currentIdx];
    
    self.definesPresentationContext = YES;
    browser.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    [self presentViewController:browser animated:NO completion:nil];
}


#pragma mark - Event Response
- (void)backToHome:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)showCommentView:(id)sender
{
    FQDCommentViewController *commentVC = [[FQDCommentViewController alloc] init];
    commentVC.post = self.post;
    [self.navigationController pushViewController:commentVC animated:YES];
}

- (void)likeThisArticle:(id)sender
{
    FQDAccountManager *accountManager = [FQDAccountManager sharedManager];
    NSString *userId = accountManager.currentUserId;
    FQDPraiseHistory *praiseHistory = [FQDPraiseHistory sharedHistory];
    FQDPost *post = self.post;
    
    NSInteger praiseCountBefore = post.praise_count;
    BOOL praisedBefore = [praiseHistory userHasPraised:post.ID userId:userId];
    BOOL praisedNow = !praisedBefore;
    FQDPraiseHistoryItem *praiseItem = [[FQDPraiseHistoryItem alloc] init];
    praiseItem.qdID = post.ID;
    praiseItem.userId = userId;
    praiseItem.praised = praisedNow;
    praiseItem.praiseType = kPraiseTypeArticle;
    
    WeakSelf;
    [[FQDPraiseHistory sharedHistory] praiseWithItem:praiseItem originalPraiseCount:praiseCountBefore updatePraiseCountBlock:^(NSInteger praiseCount) {
        post.praise_count = praiseCount;
        [weakSelf updateDetailToolbar];
        
        NSDictionary *userInfo = @{kQDailyPostDataUserInfoKey : weakSelf.post};
        NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
        [defaultCenter postNotificationName:FQDPostDataDidChangeNotification
                                     object:weakSelf userInfo:userInfo];
    }];
    
    [self playLikeArticleAnimation];
    
}

- (void)shareThisArticle:(id)sender
{
    
}

#pragma mark - Animation
- (void)setToolBarHidden:(BOOL)hidden animated:(BOOL)animated
{
    WeakSelf;
    
    CGSize backBtnSize = self.backButton.frame.size;
    CGSize toolBarSize = self.detailToolBar.frame.size;
    
    if (hidden) {
        [self.backButton mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(weakSelf.view).offset(backBtnSize.height);
        }];
        [self.detailToolBar mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(weakSelf.view).offset(toolBarSize.height);
        }];
        [self.view setNeedsLayout];
        
        CGFloat duration = (animated) ? 0.25f : 0;
        [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveEaseIn
         animations:^{
            [weakSelf.view layoutIfNeeded];
        } completion:nil];
    } else {
        [self.backButton mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(weakSelf.view).offset(-4);
        }];
        [self.detailToolBar mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(weakSelf.view);
        }];
        [self.view setNeedsLayout];
        
        CGFloat duration = (animated) ? 0.12f : 0;
        [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveEaseInOut
         animations:^{
            [weakSelf.view layoutIfNeeded];
        } completion:nil];
    }
}

- (void)playLikeArticleAnimation
{
    FQDDetailToolBarButton *likeButton = self.likeButton;
    UIView *superview = likeButton.superview;
    UIImage *likeImage = [UIImage imageNamed:@"toolbarLiked"];
    UIImageView *likedImageView = [[UIImageView alloc] initWithImage:likeImage];
    likedImageView.frame = [superview convertRect:likeButton.iconImageView.frame fromView:likeButton];
    [superview addSubview:likedImageView];
    
    [UIView animateWithDuration:0.5f animations:^{
        likedImageView.transform = CGAffineTransformMakeScale(2.5f, 2.5f);
        likedImageView.alpha = 0;
    } completion:^(BOOL finished) {
        [likedImageView removeFromSuperview];
    }];
}

#pragma mark - UIWebView Delegate Methods

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
//    FQDLog(@"loading request:%@", request);
    // WebView里的文章链接点击后使用FQDArticleDetailViewController显示
    NSString *urlString = request.URL.absoluteString;
    NSRange pathRange = [urlString rangeOfString:@"/mobile/articles/"];
    NSRange fileRange = [urlString rangeOfString:@".html" options:NSBackwardsSearch];
    if (pathRange.location != NSNotFound && fileRange.location != NSNotFound) {
        NSUInteger postIdBegin = pathRange.location+pathRange.length;
        NSRange postIdRange = NSMakeRange(postIdBegin, fileRange.location-postIdBegin);
        NSString *articleId = [urlString substringWithRange:postIdRange];
        FQDPost *post = [[FQDPost alloc] init];
        post.ID = articleId;
        FQDArticleDetailViewController *adVC = [[FQDArticleDetailViewController alloc] init];
        adVC.post = post;
        [self.navigationController pushViewController:adVC animated:YES];
        return NO;
    }
    return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [self endLoading:YES];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    FQDLog(@"load url(%@) failed:%@", [webView.request URL], [error localizedDescription]);
    [self endLoading:NO];
}

#pragma mark - UIScrollView Delegate Methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    CGPoint contentOffset = scrollView.contentOffset;
    CGSize headerSize = self.view.bounds.size;
    headerSize.height = [[UIScreen mainScreen] bounds].size.height;
    
    if (contentOffset.y > headerSize.height) {
        self.fqd_statusBarStyle = FQDStatusBarStyleDarkOpaque;
    }
    else {
        self.fqd_statusBarStyle = FQDStatusBarStyleLightTranslucent;
    }
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    CGPoint translation = [scrollView.panGestureRecognizer translationInView:scrollView.superview];
    if (translation.y > 0) {
        [self setToolBarHidden:NO animated:YES];
    } else {
        [self setToolBarHidden:YES animated:YES];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat bottomY = scrollView.contentOffset.y + scrollView.frame.size.height;
    if (bottomY >= scrollView.contentSize.height) {
        [self setToolBarHidden:NO animated:YES];
    }
}

@end
